package myzzyl.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import myzzyl.constants.ErrorConstants;
import myzzyl.domain.dto.NursingPlanDto;
import myzzyl.domain.pojo.NursingPlan;
import myzzyl.domain.pojo.NursingProjectPlan;
import myzzyl.domain.vo.NursingPlanVo;
import myzzyl.domain.vo.NursingProjectPlanVo;
import myzzyl.exception.BusinessException;
import myzzyl.response.PageResponse;
import myzzyl.service.NursingPlanService;
import myzzyl.mapper.NursingPlanMapper;
import myzzyl.service.NursingProjectPlanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 33249
* @description 针对表【nursing_plan(护理计划表)】的数据库操作Service实现
* @createDate 2025-08-10 10:20:23
*/
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan>
    implements NursingPlanService{

    @Autowired
    private NursingProjectPlanService nursingProjectPlanService;


    /**
     * 分页获取所有护理计划
     * @param name 护理计划名称
     * @param status 状态
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 返回值
     */
    @Override
    public PageResponse<NursingPlanVo> getAll(String name, Integer status, Integer pageNum, Integer pageSize) {
        // 创建分页对象
        Page<NursingPlan> page = new Page<>(pageNum, pageSize);

        // 添加排序字段
        page.addOrder(OrderItem.asc("sort_no"), OrderItem.desc("create_time"));

        // 自定义分页查询
        IPage<NursingPlanVo> nursingPlanVoIPage = baseMapper.selectNursingPlanVo(page, name, status);

        // 封装分页响应格式对象返回
        return new PageResponse<>(nursingPlanVoIPage.getPages(), nursingPlanVoIPage.getTotal(),
                nursingPlanVoIPage.getRecords());
    }


    /**
     * 获取护理计划详情
     * @param id 护理计划id
     * @return 返回值
     */
    @Override
    public NursingPlanVo getInfo(Integer id) {
        // 查询护理计划是否存在
        NursingPlan nursingPlan = getById(id);
        if(nursingPlan == null) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_IS_NOT_EXIST);
        }

        // 查询当前护理计划下的项目
        List<NursingProjectPlanVo> projectPlans = nursingProjectPlanService.selectByPlanId(id);

        // 构造Vo对象返回
        NursingPlanVo nursingPlanVo = new NursingPlanVo();
        BeanUtils.copyProperties(nursingPlan, nursingPlanVo);
        nursingPlanVo.setProjectPlans(projectPlans);
        return nursingPlanVo;
    }

    /**
     * 新增护理计划
     * @param nursingPlanDto 护理计划表单请求包装类
     * @return 返回值
     */
    @Override
    @Transactional
    public boolean add(NursingPlanDto nursingPlanDto) {
        // 判断护理计划名称是否为空
        if (StrUtil.isBlank(nursingPlanDto.getPlanName())) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_NAME_IS_NULL);
        }

        // 查询护理计划是否已经存在
        if (lambdaQuery().eq(NursingPlan::getPlanName, nursingPlanDto.getPlanName()).exists()) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_IS_ALREADY_EXIST);
        }

        // 新增护理计划
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);

        boolean isSuccess = save(nursingPlan);
        if(!isSuccess) {
            return false;
        }

        // 判断护理计划项目是否为空
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        if(CollectionUtil.isEmpty(projectPlans)) {
            throw new BusinessException(ErrorConstants.NURSING_PROJECT_PLAN_IS_NULL);
        }
        // 设置护理计划id
        projectPlans.forEach(nursingProjectPlan -> nursingProjectPlan.setPlanId(nursingPlan.getId()));

        // 批量新增护理计划下的护理项目
//        return nursingProjectPlanMapper.batchInsert(projectPlans) == projectPlans.size();
        return nursingProjectPlanService.saveBatch(projectPlans);
    }


    /**
     * 编辑护理计划
     * @param nursingPlanDto 护理计划表单请求包装类
     * @return 返回值
     */
    @Override
    @Transactional
    public boolean edit(NursingPlanDto nursingPlanDto) {
        // 判断护理计划名是否为空
        if (StrUtil.isBlank(nursingPlanDto.getPlanName())) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_NAME_IS_NULL);
        }

        // 查询护理计划是否已经存在（除去自己）
        if (lambdaQuery()
                .eq(NursingPlan::getPlanName, nursingPlanDto.getPlanName())
                .ne(NursingPlan::getId, nursingPlanDto.getId())
                .exists()) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_IS_ALREADY_EXIST);
        }

        // 更新护理计划
        boolean isSuccess = lambdaUpdate()
                .set(StrUtil.isNotBlank(nursingPlanDto.getPlanName()), NursingPlan::getPlanName, nursingPlanDto.getPlanName())
                .set(nursingPlanDto.getSortNo() != null, NursingPlan::getSortNo, nursingPlanDto.getSortNo())
                .set(nursingPlanDto.getStatus() != null, NursingPlan::getStatus, nursingPlanDto.getStatus())
                .eq(NursingPlan::getId, nursingPlanDto.getId())
                .update();
        if(!isSuccess) {
            return false;
        }


        // 根据计划id删除项目
        nursingProjectPlanService.deleteByPlanId(nursingPlanDto.getId());

        // 判断护理计划项目是否为空
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        if(CollectionUtil.isEmpty(projectPlans)) {
            throw new BusinessException(ErrorConstants.NURSING_PROJECT_PLAN_IS_NULL);
        }
        // 设置护理计划id
        projectPlans.forEach(nursingProjectPlan -> nursingProjectPlan.setPlanId(nursingPlanDto.getId()));

        // 批量新增护理计划下的护理项目
//        return nursingProjectPlanMapper.batchInsert(projectPlans) == projectPlans.size();
        return nursingProjectPlanService.saveBatch(projectPlans);
    }


    /**
     * 删除护理计划
     * @param id 护理计划id
     * @return 返回值
     */
    @Override
    @Transactional
    public boolean deleteNursingPlanById(Integer id) {
        // 查询护理计划是否存在
        if(!lambdaQuery().eq(NursingPlan::getId, id).exists()) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_IS_NOT_EXIST);
        }

        // 删除护理计划下的项目
        nursingProjectPlanService.deleteByPlanId(id);

        // 删除护理计划
        return baseMapper.deleteById(id) > 0;
    }


    /**
     * 启用或禁用护理计划
     * @param id 护理计划id
     * @param status 需要更新的护理计划状态
     * @return 返回值
     */
    @Override
    public boolean enableOrDisableNursingPlan(Integer id, Integer status) {
        // 查询护理计划是否存在
        if(!lambdaQuery().eq(NursingPlan::getId, id).exists()) {
            throw new BusinessException(ErrorConstants.NURSING_PLAN_IS_NOT_EXIST);
        }

        // 更新护理计划状态
        return lambdaUpdate()
                .set(status != null, NursingPlan::getStatus, status)
                .eq(NursingPlan::getId, id)
                .update();
    }


    /**
     * 获取所有护理计划
     * @return 返回值
     */
    @Override
    public List<NursingPlanVo> listAll() {
        // 创建分页对象（不带分页参数，查询全部）
        Page<NursingPlan> page = new Page<>();

        // 添加排序字段
        page.addOrder(OrderItem.asc("sort_no"), OrderItem.desc("create_time"));

        return baseMapper.selectNursingPlanVo(page, null, null).getRecords();
    }
}




